from django import forms
from sa.forms.bootstrap import BootStrapForm
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from sa import models
# 自定义了一个 ColorRadioSelect 插件
from sa.forms.widgets import ColorRadioSelect
from django.utils import timezone


class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color', 'big_project']
    SR_No = forms.CharField(label='SR_No#',
                            validators=[RegexValidator(regex=r'^[0-9]+$', message='只能输入数字')])

    # big_project = forms.BooleanField(widget=forms.RadioSelect, required=False)

    class Meta:
        model = models.Project
        fields = [
            'SR_No', 'category', 'software',
            'version', 'server_num', 'mfd_num', 'printer_num', 'start_date',
            'big_project', 'value', 'actors', 'color', 'desc'

        ]
        widgets = {
            'start_date': forms.DateInput(attrs={'type': 'date', 'xx': '123'}),
            'end_date': forms.DateInput(attrs={'type': 'date', 'yy': '456'}),
            # 'end_date': forms.DateTimeInput(attrs={'type': 'datetime-local'}),
            # color 使用自定义的 ColorRadioSelect 插件
            'color': ColorRadioSelect(attrs={"class": "color-radio"}),
            'big_project': forms.CheckboxInput(attrs={'class': 'checkbox'})
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_SR_No(self):
        SR_No = self.cleaned_data.get('SR_No')
        exists = models.Project.objects.filter(SR_No=SR_No).exists()
        if exists:
            raise ValidationError('此SR号码已经存在！')
        return SR_No

    def clean_start_date(self):
        start_date = self.cleaned_data.get('start_date')
        # 使用 timezone.now() 而不是 datetime.now() 以确保时区一致性
        # 将 timezone.now() 转换为 timezone.now().date() 只比较日期
        # date_now = datetime.date()
        date_now = timezone.now().date()
        if start_date > date_now:
            raise ValidationError('开始日期不能大于当前日期')
        return start_date

    def clean_big_project(self):
        category = self.cleaned_data.get('category')
        big_project = self.cleaned_data.get('big_project')
        if big_project:
            if category not in ['新购实施', '添加设备', '添加模块']:
                raise ValidationError('项目类型不正确')
        return big_project

    def clean_value(self):
        big_project = self.cleaned_data.get('big_project')
        value = self.cleaned_data.get('value')
        if big_project and value == 0:
            raise ValidationError('大项目的金额不正确！')
        return value
